﻿using NetworkPower.DataModel.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace NetworkPower.UI
{
    /// <summary>
    /// Interaction logic for DefineDevice.xaml
    /// </summary>
    public partial class DefineDevice : Window
    {
        private NetworkPowerContext context = new NetworkPowerContext();
        private Project project = null;
        private List<LoopLine> SelectedTerminalNos = new List<LoopLine>();
        private Device SelectedDevice = null;

        public DefineDevice(Project project)
        {
            InitializeComponent();
            this.project = project;
            this.txtProjectName.Text = project.ProjectName;
            LoadVoltages();
        }

        private void LoadVoltages()
        {
            var datasouce = context.Voltages.Where(v => v.ProjectID == project.ProjectID).OrderBy(v => v.VoltageValue).ToList();
            cbVoltage.ItemsSource = datasouce;
            cbVoltage.DisplayMemberPath = "VoltageValue";
        }

        private void cbVoltage_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbVoltage.SelectedItem != null)
            {
                var selecteVoltage = cbVoltage.SelectedItem as Voltage;
                var datasouce = context.SeperatorTypes.Where(s => s.VoltageID == selecteVoltage.VoltageID).OrderBy(s => s.SeperatorValue).OrderBy(s => s.SeperatorValue).ToList();
                cbSeperatorType.ItemsSource = datasouce;
                cbSeperatorType.DisplayMemberPath = "SeperatorValue";
            }
            else
            {
                cbSeperatorType.ItemsSource = null;
            }
        }

        private void cbSeperatorType_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbSeperatorType.SelectedItem != null)
            {
                var selectedSeperatorType = cbSeperatorType.SelectedItem as SeperatorType;
                var datasource = context.UnitComposites.Where(uc => uc.SeperatorTypeId == selectedSeperatorType.SeperatorTypeID).ToList();
                lbUnit.ItemsSource = datasource;
                lbUnit.DisplayMemberPath = "UnitAndSeperatorName";
            }
            else
            {
                lbUnit.ItemsSource = null;
            }
        }

        private void LoadEquipment(Unit selectedUnit)
        {
            var datasouce = context.Equipments.Where(e => e.UnitCompositeId == selectedUnit.UnitID).ToList();
            cbCabinet.ItemsSource = datasouce;
            cbCabinet.DisplayMemberPath = "EquipmentName";
        }

        private void cbCabinet_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbCabinet.SelectedItem != null)
            {
                LoadTerminalNo();
                LoadDevice();
            }
            else
            {
                lsTerminalNos.ItemsSource = null;
                dgDevice.ItemsSource = null;
            }

            lsSelectedTerminalNos.ItemsSource = null;
            txtDeviceName.Text = string.Empty;
            txtDeviceType.Text = string.Empty;
        }

        private void LoadTerminalNo()
        {
            var selectedEquipment = cbCabinet.SelectedItem as Equipment;
            var datasouce = context.LoopLines.Where(l => l.EquipmentId == selectedEquipment.EquipmentID && l.IsTitle).OrderBy(l => l.TerminalNo).ToList();
            foreach (LoopLine loopLine in SelectedTerminalNos)
            {
                if (datasouce.Contains(loopLine))
                {
                    datasouce.Remove(loopLine);
                }
            }
            lsTerminalNos.ItemsSource = null;
            lsTerminalNos.ItemsSource = datasouce;
            lsTerminalNos.DisplayMemberPath = "TerminalNo";
        }

        private void toRight_Click(object sender, RoutedEventArgs e)
        {
            foreach (var item in lsTerminalNos.SelectedItems)
            {
                LoopLine loopLine = item as LoopLine;
                if (!SelectedTerminalNos.Contains(loopLine))
                {
                    SelectedTerminalNos.Add(loopLine);
                }
            }
            LoadTerminalNo();
            LoadSelectedTerminalNo();
        }

        private void toLeft_Click(object sender, RoutedEventArgs e)
        {
            foreach (var item in lsSelectedTerminalNos.SelectedItems)
            {
                LoopLine loopLine = item as LoopLine;
                if (SelectedTerminalNos.Contains(loopLine))
                {
                    SelectedTerminalNos.Remove(loopLine);
                }
            }
            LoadTerminalNo();
            LoadSelectedTerminalNo();
        }

        private void btnSaveDevice_Click(object sender, RoutedEventArgs e)
        {
            if (lsSelectedTerminalNos.Items.Count < 1)
            {
                MessageBox.Show("请选择设备屏柜所含端子排");
                return;
            }
            if (txtDeviceName.Text.Trim().Length < 1)
            {
                MessageBox.Show("请输入设备名称");
                return;
            }
            if (txtDeviceType.Text.Trim().Length < 1)
            {
                MessageBox.Show("请输入设备名类型");
                return;
            }

            string selectedTerminalNos = string.Join(",", SelectedTerminalNos.Select(s => s.LoopLineId).ToArray());
            string childLooplineIDs = string.Empty;

            var childList = new List<string>();

            var deviceloopline = string.Empty;
            for (int i = 0; i < SelectedTerminalNos.Count(); i++)
            {
                var terminalNo = SelectedTerminalNos[i].TerminalNo;
                var eqid = SelectedTerminalNos[i].EquipmentId;
                var fatherTerminalNo = context.LoopLines.SingleOrDefault(o => o.TerminalNo == terminalNo && o.EquipmentId ==
            eqid).TerminalNo;

                childList.Add(string.Join(",", context.LoopLines.Where(o => o.FatheTerminalNo == fatherTerminalNo
                && o.EquipmentId == eqid).Select(s => s.LoopLineId).ToArray()));

            }

            if (childList.Count > 1)
            {
                foreach (var child in childList)
                {
                    deviceloopline += child + ",";
                }
                deviceloopline = deviceloopline.Remove(deviceloopline.Length - 1, 1);
            }
            else
            {
                deviceloopline = childList.FirstOrDefault();
            }


            var selectedEquipment = cbCabinet.SelectedItem as Equipment;
            if (SelectedDevice == null)
            {
                Device device = new Device()
                {
                    DeviceID = Guid.NewGuid(),
                    DeviceName = txtDeviceName.Text.Trim(),
                    DeviceType = txtDeviceType.Text.Trim(),
                    LoopLineIds = selectedTerminalNos,
                    EquipmentId = selectedEquipment.EquipmentID,
                    ChildLoopLineIds = deviceloopline
                };


                context.Devices.Add(device);

                //var list = SelectedTerminalNos.Select(s => s.LoopLineId).ToList();
                //foreach (var item in list)
                //{
                //    var deveiceLooplineList = new List<string>();
                //}
            }
            else
            {
                context.Devices.Remove(SelectedDevice);
                context.SaveChanges();
                SelectedDevice.DeviceName = txtDeviceName.Text.Trim();
                SelectedDevice.DeviceType = txtDeviceType.Text.Trim();
                SelectedDevice.LoopLineIds = selectedTerminalNos;
                SelectedDevice.ChildLoopLineIds = deviceloopline;
                context.Devices.Add(SelectedDevice);
            }
            context.SaveChanges();
            LoadDevice();
            SelectedTerminalNos.Clear();
            LoadTerminalNo();
            LoadSelectedTerminalNo();
            this.txtDeviceName.Text = string.Empty;
            this.txtDeviceType.Text = string.Empty;
            SelectedDevice = null;
        }

        private void LoadSelectedTerminalNo()
        {
            lsSelectedTerminalNos.ItemsSource = null;
            lsSelectedTerminalNos.ItemsSource = SelectedTerminalNos.OrderBy(s => s.TerminalNo);
            lsSelectedTerminalNos.DisplayMemberPath = "TerminalNo";
        }

        private void LoadDevice()
        {
            if (cbCabinet.SelectedItem != null)
            {
                var selectedEquipment = cbCabinet.SelectedItem as Equipment;
                var datasouce = context.Devices.Where(d => d.EquipmentId == selectedEquipment.EquipmentID).ToList();
                dgDevice.ItemsSource = null;
                dgDevice.ItemsSource = datasouce;
            }
        }

        private void dgDevice_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (dgDevice.SelectedItems.Count > 0)
            {
                SelectedDevice = dgDevice.SelectedItems[0] as Device;
                this.txtDeviceName.Text = SelectedDevice.DeviceName;
                this.txtDeviceType.Text = SelectedDevice.DeviceType;
                FillSelectedTerminalNo(SelectedDevice.LoopLineIds);
                LoadTerminalNo();
                LoadSelectedTerminalNo();
            }
        }

        private void FillSelectedTerminalNo(string terminalIds)
        {
            SelectedTerminalNos.Clear();
            if (!string.IsNullOrEmpty(terminalIds))
            {
                var ids = terminalIds.Split(',');
                foreach (string id in ids)
                {
                    var loopline = context.LoopLines.Where(l => l.LoopLineId.ToString() == id).FirstOrDefault();
                    SelectedTerminalNos.Add(loopline);
                }
            }
        }

        private void lbUnit_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (lbUnit.SelectedItems.Count > 0)
            {
                var selectedUnitComposite = lbUnit.SelectedItems[0] as UnitComposite;
                var datasource = context.Equipments.Where(uc => uc.UnitCompositeId == selectedUnitComposite.UnitCompositeId).OrderBy(eq => eq.EquipmentName).ToList();
                cbCabinet.ItemsSource = null;
                cbCabinet.ItemsSource = datasource;
                cbCabinet.DisplayMemberPath = "EquipmentName";
            }
            else
            {
                cbCabinet.ItemsSource = null;
            }
        }
    }

    public class TerminalValueConvert : IValueConverter
    {
        private NetworkPowerContext context = new NetworkPowerContext();
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string result = string.Empty;
            if (value != null)
            {
                string ids = value.ToString();
                result = GetTerminalNo(ids);
            }
            return result;
        }

        private string GetTerminalNo(string terminalIds)
        {
            List<LoopLine> looplines = new List<LoopLine>();
            if (!string.IsNullOrEmpty(terminalIds))
            {
                var ids = terminalIds.Split(',');
                foreach (string id in ids)
                {
                    var loopline = context.LoopLines.Where(l => l.LoopLineId.ToString() == id).FirstOrDefault();
                    looplines.Add(loopline);
                }
            }
            return string.Join(",", looplines.Select(l => l.TerminalNo).ToArray());
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
